package com.zerox.springsecuritydemo329.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zerox.springsecuritydemo329.pojo.LoginUser;
import com.zerox.springsecuritydemo329.pojo.SysUser;
import com.zerox.springsecuritydemo329.service.SysUserService;
import com.zerox.springsecuritydemo329.mapper.SysUserMapper;
import com.zerox.springsecuritydemo329.utils.JwtUtil;
import com.zerox.springsecuritydemo329.utils.RedisCache;
import io.jsonwebtoken.Jws;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Component
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
    implements SysUserService{

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public String login(SysUser sysUser) {
        UsernamePasswordAuthenticationToken authRequest
                = new UsernamePasswordAuthenticationToken(sysUser.getUserName(),sysUser.getPassword());

        Authentication authenticate = authenticationManager.authenticate(authRequest);

        if (Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }

        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();

        //登陆成功,创建一个token(身份卡),jwt
//        String token = "23rewfeot43rjwepmfw";
        String token = JwtUtil.createJWT(loginUser.getSysUser().getId().toString());

        //把登录的用户存到缓存里
        //key的规范，login:id
        redisCache.setCacheObject("login:"+loginUser.getSysUser().getId(),loginUser,1, TimeUnit.HOURS);
        return token;
    }

    @Override
    public void logout() {
        // 拿到当前用户
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        // 从缓存中删除用户
        redisCache.deleteObject("login:"+loginUser.getSysUser().getId());
    }
}